import { EditorConfig } from '@/editor/model/editor-config';
import { DocService } from '@/service/doc.service';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-editor-md-demo',
  templateUrl: './editor-md-demo.component.html',
  styleUrls: ['./editor-md-demo.component.less']
})
export class EditorMdDemoComponent implements OnInit {

  blog_content: string = "";
  validateForm!: FormGroup;
  docID: string;
  conf = new EditorConfig();


  constructor(
    private fb: FormBuilder,
    private docService: DocService,
    private route: ActivatedRoute,
    private router: Router,
    private message: NzMessageService,
  ) {
    this.docID = route.snapshot.paramMap.get('id') || "";
  }

  ngOnInit(): void {
    this.conf.height = '100%';

    let group = {
      docID: ['', []],
      docName: ['', [Validators.required]],
      docCont: ['', [Validators.required]],
    }
    this.validateForm = this.fb.group(group);


    if (this.docID.length) {
      this.docService.getDocByID(this.docID).subscribe(el => {
        let p1 = {
          docID: this.docID,
          docName: el.data.doc_name,
          docCont: 'loadding'
        };
        this.validateForm.patchValue(p1)
        let path = el.data.doc_path;
        this.docService.getDocConctentByPath(path).subscribe(text => {
          p1.docCont = text;
          this.validateForm.patchValue(p1)
        })
      })
    }

  }

  syncModel(str: string): void {
    this.blog_content = str;
  }

  submitForm(): void {

    if (!this.validateForm.valid) {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
      return;
    }

    this.docService.saveDoc(this.validateForm.value).subscribe(el => {
      if (el.flag) {
        this.message.create('success', el.message);
        this.router.navigateByUrl(`layout/docs/list`);
      } else {
        this.message.create('error', el.message);
      }
    });
  }
}
